package com.legsem.legstar;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.Set;

import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;

/**
 * Small utilities.
 *
 */
public class LegStarUtil {
    
    /**
     * Utility class.
     */
    private LegStarUtil() {
        
    }
    
    /**
     * The JAAS subject toString prints on multiple lines cluttering logs. Here we print on a single line.
     * @param subject the JAAS subject
     * @return a string representation of the subject.
     */
    public static String toString(Subject subject) {
        if (subject == null) {
            return null;
        }
        StringBuilder sb = new  StringBuilder();
        AccessController
                .doPrivileged(new PrintCredentialAction(subject, sb));
        return sb.toString();
        
    }

    /**
     * Print credentials from a subject.
     * <p/>
     * This needs to run as a privileged action.
     * 
     */
    private static class PrintCredentialAction implements
            PrivilegedAction < PasswordCredential > {
        Subject subject;
        StringBuilder sb;

        PrintCredentialAction(Subject subject, StringBuilder sb) {
            this.subject = subject;
            this.sb = sb;
        }

        public PasswordCredential run() {
            Set < PasswordCredential > pcs = subject
                    .getPrivateCredentials(PasswordCredential.class);
            Iterator < PasswordCredential > it = pcs.iterator();
            boolean first = true;
            while (it.hasNext()) {
                if (first) {
                    first = false;
                } else {
                    sb.append(", ");
                }
                PasswordCredential pc = it.next();
                sb.append("UserName: " + pc.getUserName() + "[" + pc.getManagedConnectionFactory().getClass().getName() + "]");
            }
            return null;
        }

    }
}
